package com.itao.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Desc 消息队列配置
 * @Author LiuRongQiang
 * @Date 2021/12/21 12:55
 */
@Slf4j
@Configuration
public class RabbitMqConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 生产端消息确认
     */
    @Bean
    public RabbitTemplate getTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter){
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // 消息发送到交换器Exchange后触发回调
        template.setConfirmCallback((correlationData, ack, cause) -> {
            //  可以进行消息入库操作
            log.info("消息唯一标识 correlationData = {}", correlationData);
            log.info("确认结果 ack = {}", ack);
            log.info("失败原因 cause = {}", cause);
        });
        // 配置这个，下面的ReturnCallback 才会起作用
        template.setMandatory(true);
        // 如果消息从交换器发送到对应队列失败时触发（比如 根据发送消息时指定的routingKey找不到队列时会触发）
        template.setReturnsCallback((message) -> {
            //  可以进行消息入库操作
            log.info("消息主体 message = {}", message.getMessage());
            log.info("回复码 replyCode = {}", message.getReplyCode());
            log.info("回复描述 replyText = {}", message.getReplyText());
            log.info("交换机名字 exchange = {}", message.getExchange());
            log.info("路由键 routingKey = {}", message.getRoutingKey());
        });
        template.setMessageConverter(messageConverter);
        return template;
    }
}